from PySide6.QtCore import QObject, Signal
from typing import Dict, Optional
import json
import os

class ViewController(QObject):
    """视图控制器，管理视图状态和交互"""
    view_state_changed = Signal(str, dict)  # 信号：视图状态改变

    def __init__(self):
        super().__init__()
        self._view_states: Dict[str, dict] = {}
        self._config_file = "view_config.json"
        self._load_config()

    def save_view_state(self, view_name: str, state: dict):
        """保存视图状态"""
        self._view_states[view_name] = state
        self.view_state_changed.emit(view_name, state)
        self._save_config()

    def get_view_state(self, view_name: str) -> Optional[dict]:
        """获取视图状态"""
        return self._view_states.get(view_name)

    def _save_config(self):
        """保存配置到文件"""
        try:
            with open(self._config_file, 'w') as f:
                json.dump(self._view_states, f)
        except Exception as e:
            print(f"Error saving config: {e}")

    def _load_config(self):
        """从文件加载配置"""
        try:
            if os.path.exists(self._config_file):
                with open(self._config_file, 'r') as f:
                    self._view_states = json.load(f)
        except Exception as e:
            print(f"Error loading config: {e}")
            self._view_states = {} 